<template>
  <div class="gov-form-upload">
    <template v-if="handleType === 'scan'">
      <span class="scan-text">{{ selectLabel }}</span>
    </template>
    <template v-else>
      <el-upload
        class="upload"
        :on-preview="handlePreview"
        action="/api/v1/file/ftp"
        :on-success="handleSuccess"
        :limit="1"
        :file-list="fileList"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
    </template>
  </div>
</template>

<script>
  export default {
    components: {},
    props: {
      // clone克隆、edit编辑、scan查看
      handleType: {
        type: String
      },
      action: {
        type: Object,
        default: () => {
          return {};
        }
      },
      selected: {
        type: Array,
        default: () => {
          return [];
        }
      }
    },

    data() {
      return {
        fileList: [],
        selectLabel: ''
      };
    },
    watch: {
      selected: {
        handler(val) {
          if (val && val.length > 0) {
            this.fileList = val.map((e) => {
              const { fileName, filePath, newName } = e;
              return {
                name: fileName,
                fileName,
                filePath,
                newName
              };
            });
          } else {
            this.fileList = [];
          }
          this.filterHande(this.fileList);
        }
      }
    },
    computed: {},
    methods: {
      handleSuccess(res, file, fileList) {
        const { result, message } = res;
        if (!result) {
          this.$message.error(message);
          this.fileList = [];
          return;
        }

        const { fileName, filePath, newName } = result;
        this.$emit('selectChange', { eicCode: this.action.eicCode, value: [{ fileName, filePath, newName }] });
      },
      handlePreview(file) {
        const { fileName, filePath, newName } = file;
        const url = `/api/v1/file/ftp?fileName=${fileName}&filePath=${filePath}&newName=${newName}`;
        window.open(url);
      },
      filterHande() {
        if (this.handleType !== 'scan') {
          return;
        }

        const list = [];
        this.fileList.forEach((e) => {
          list.push(e.name);
        });
        this.selectLabel = list.join(',');
      }
    },
    created() {},
    mounted() {}
  };
</script>
<style lang="scss">
  .gov-form-upload {
    .upload {
      margin: 10px;
      display: flex;
      align-items: center;
      .el-upload-list {
        .el-upload-list__item {
          margin: 0;
        }
      }
    }
  }
</style>
